<?php
namespace app\shop\controller;

use app\common\controller\Shop;
use app\common\library\util\Ems;
use app\common\library\util\PosterUtil;
use app\common\library\util\QRcodeUtil;
use app\common\library\util\Secure;
use think\Request;
use app\common\model\Business\Source;
use fast\Random;
use app\common\library\util\Token;
use app\common\model\Business\Address;
use app\common\model\Business\Business as BusinessBusiness;
use app\common\model\Business\Collection;
use app\common\model\Business\Commission;
use app\common\model\Business\Record;
use app\common\model\Order\Order;
use app\common\model\Pay;
use app\common\model\Region;

use Exception;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

class Business extends Shop
{
    protected $model = null;
    public function __construct(Request $request)
    {
        $this->model = new BusinessBusiness();
        $this->noLogin = ['login','check'];
        parent::__construct($request);
    }
    public function login()
    {
        $mobile = $this->request->post("mobile","","trim");
        $passwordInput = $this->request->post("password","","trim");
        $business = $this->model->where('mobile',$mobile)->find();
        $result = [];
        if($business){
            $password = $business["password"];
            $salt = $business["salt"];
            if(md5(md5($passwordInput) . $salt)==$password){
                $token = Token::generateToken([
                    "id" => $business["id"],
                    "mobile" => $business["mobile"],
                ]);
                $result = [
                    'code'=>1,
                    'msg'=>'登录成功',
                    'data'=>[
                        'business'=>$business,
                        'token'=>$token,
                    ],
                ];
            }else{
                $result = [
                    'code'=>0,
                    'msg'=>'登录失败',
                    'data'=>null,
                ];
            }
        }else{
            $nickname = substr($mobile,0,3).'****'.substr($mobile,strlen($mobile)-4,strlen($mobile));
            $salt = Random::alnum(10);
            $password = md5(md5($passwordInput) . $salt);
            $sourceid = Source::whereLike('name','%家居商城%')->find()['id'];
            $token = $this->request->post("token",'',"trim");
            $data = [
                'mobile' => $mobile,
                'nickname' => $nickname,
                'password' => $passwordInput,
                'salt' => $salt,
                'gender' => 0,
                'sourceid' => $sourceid,
                'deal' => 0,
                'money' => 0,
                'auth' => 0,
            ];
            if($token){
                $parentMobile = Secure::decrypt($token);
                $parent = $this->model->where('mobile',$parentMobile)->find();
                if($parent){
                    $data['parentid'] = $parent['id'];
                }
            }
            $res = false;
            Db::startTrans();
            try {
                $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $this->validateFailException()->validate($data,$validate);
                // $result = $this->validate($data,"app\\common\\validate\\Business\\Business");
                $data['password'] = $password;
                $res = $this->model->create($data);
                // $token = Token::generateToken([
                //     "id" => $business["id"],
                //     "mobile" => $mobile,
                // ]);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $result = [
                    'code'=>0,
                    'msg'=>$e->getMessage(),
                    'data'=>null,
                ];
                return $result;
            }
            if ($res === false) {
                $result = [
                    'code'=>0,
                    'msg'=>'注册失败',
                    'data'=>null,
                ];
            }else{
                $token = Token::generateToken([
                    "id" => $res["id"],
                    "mobile" => $res["mobile"],
                ]);
                $result = [
                    'code'=>1,
                    'msg'=>'注册成功',
                    'data'=>[
                        'business'=>$res,
                        'token'=>$token,
                    ],
                ];
            }
        }
        return $result;
    }

    public function check()
    {
        if(!$this->request->isGet())return ['code'=>0,'msg'=>'请求错误'];
        $token = $this->request->get('token');
        return $this->isLogin($token);
    }
    public function profile()
    {
        if(!$this->request->isPost())return ['code'=>0,'msg'=>'请求错误'];
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->post();
        if($this->model->where(['id'=>['<>',$this->business['id']],'mobile'=>$params['mobile']])->find())
        {
            $this->error('手机号已存在');
        }
        if($this->model->where(['id'=>['<>',$this->business['id']],'email'=>$params['email']])->find())
        {
            $this->error('邮箱已存在');
        }
        if($params['email']==$this->business['email']){
            unset($params['email']);
        }else{
            $params['auth'] = 0;
        }
        $code = isset($params['code'])?$params['code']:0;
        $region = Region::where('code',$code)->find();
        if($region){
            $parentpath = explode(',',$region['parentpath'].',,');
            $params['province'] = $parentpath[0];
            $params['city'] = $parentpath[1];
            $params['district'] = $parentpath[2];
        }
        // return $params;
        $result = false;
        $preImgFile = '';
        $curImgFile = '';
        Db::startTrans();
        try {
            $ispassword = isset($params['password']);
            $ispassword||$params['password'] = '123456';
            $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $this->validateFailException()->validate($params,$validate);
            if(!$ispassword){
                unset($params['password']);
            }else{
                $params['salt'] = Random::alnum(10);
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            //上传图片
            $status = $this->upload();
            if($status['code']==1){
                $preImgFile = ROOT_PATH . 'public' . $this->business['avatar'];
                $curImgFile = ROOT_PATH . 'public' . $status['msg'];
                $params['avatar'] = $status['msg'];
            }else if($status['code']==2){
                throw new FileException($status['msg']);
            }
            $result = $this->business->allowField(true)->isUpdate(true)->save($params,['id'=>$this->business['id']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            if($curImgFile&&is_file($curImgFile)){
                unlink($curImgFile);
            }
            $this->error($e->getMessage());
        }
        if($preImgFile&&is_file($preImgFile)){
            unlink($preImgFile);
        }
        if ($result === false) {
            $this->error('修改失败');
        }
        $this->success('修改成功',null,$this->business);
    }
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('avatar');
        $status = ['code'=>0];
        if(!$file){
            $status['msg'] = '';
            return $status;
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . '/' . 'uploads');
        if($info){
            $status['code'] = 1;
            $status['msg'] = '/' . 'uploads' . '/' . $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            $status['code'] = 2;
            $status['msg'] = $file->getError();
        }
        return $status;
    }
    public function auth()
    {
        
        if($this->business['auth']){
            return $this->success('邮箱已认证,无需重复验证');
        }
        if($this->request->isGet()){
            $source = Source::where('id',$this->business['sourceid'])->find();
            if(!$source)return $this->error('平台出错');
            $status = Ems::send($this->business['email'],$source['name']);
            $this->result(null,$status['code'],$status['msg']);
        }
        $status = Ems::checkCode($this->business['email'],$this->request->post('vercode'));
        if($status['code']==1){
            $this->business['auth'] = 1;
            $this->business->save();
            return $this->success($status['msg']);
        }else{
            return $this->error($status['msg']);
        }
    }
    public function address()
    {
        $where = ['busid'=>$this->business['id']];
        if($this->request->isGet())
        {
            $id = $this->request->get('id');
            if($id){
                $where['id'] = $id;
                return Address::where($where)->find();
            }
            return Address::where($where)->select();
        }else if($this->request->isDelete())
        {
            $id = $this->request->get('id');
            $where['id'] = $id;
            $address = Address::where($where)->find();
            $count = 0;
            Db::startTrans();
            try {
            $isDefault = ($address['status']=='1');
            $count = $address->delete();
            if($isDefault){
                $this->defaultAddressEdit('delete',$id);
            }
            Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($count){
                $this->success('删除成功');
            }
            $this->error('删除失败');
        }else if($this->request->isPut())
        {
            $id = $this->request->get('id');
            
            $where['id'] = $id;
            $address = Address::where($where)->find();
            if(!$address)$this->error('找不到地址');
            $params = $this->request->put();
            $result = '';
            Db::startTrans();
            try {
                if(empty($params)){
                    $address['status'] = '1';
                    $result = $address->isUpdate(true)->save();
                    $this->defaultAddressEdit('put',$id,$address['status']);
                }else{
                    $params = $params['values'];
                    $address['consignee'] = $params['name']??'';
                    $address['address'] = $params['addressDetail'];
                    $address['mobile'] = $params['tel'];
                    $isDefault = !($address['status'] == ($params['isDefault']?'1':'0'));
                    $address['status'] = $params['isDefault']?'1':'0';
        
                    $code = $params['areaCode'];
                    $region = Region::where('code',$code)->find();
                    if($region){
                        $parentpath = explode(',',$region['parentpath'].',,');
                        $address['province'] = $parentpath[0];
                        $address['city'] = $parentpath[1];
                        $address['district'] = $parentpath[2];
                    }
                    $result = $address->isUpdate(true)->save();
                    if($isDefault){
                        $this->defaultAddressEdit('put',$id,$address['status']);
                    }
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($result){
                $this->success('修改成功');
            }
            $this->error('无法修改');
        }else if($this->request->isPost())
        {
            $params = $this->request->post();
            $result = '';
            if(!isset($params['values'])){
                $this->error('数据不能为空');
            }else{
            Db::startTrans();
            try {
                $address = [];
                $params = $params['values'];
                $address['busid'] = $this->business['id'];
                $address['consignee'] = $params['name']??'';
                $address['address'] = $params['addressDetail']??'';
                $address['mobile'] = $params['tel']??'';
                $isDefault = $params['isDefault']=='1';
                $address['status'] = $params['isDefault']?1:0;
    
                $code = $params['areaCode'];
                $region = Region::where('code',$code)->find();
                if($region){
                    $parentpath = explode(',',$region['parentpath'].',,');
                    $address['province'] = $parentpath[0];
                    $address['city'] = $parentpath[1];
                    $address['district'] = $parentpath[2];
                }
                $result = Address::create($address);
                if($isDefault){
                    $this->defaultAddressEdit('post',$result['id'],$address['status']);
                }else if(Address::count()==1){
                    $this->defaultAddressEdit('post',$result['id'],'0');
                }
                Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if($result){
                    $this->success('创建成功');
                }
                $this->error('创建失败');
            }
        }
    }
    private function defaultAddressEdit($action,$addressid,$status=null)
    {
        $where = ['busid'=>$this->business['id']];
        if($action=='delete'||$status=='0')
        {
            $address = Address::where($where)->find();
            if(!$address)return;
            $address['status'] = '1';
            $address->isUpdate(true)->save();
        }else{
            $where['id'] = ['<>',$addressid];
            $addressModel = new Address();
            $defaultAddress = $addressModel->where($where)->select();
            if(!$defaultAddress)return;
            foreach($defaultAddress as $address)
            {
                $address['status'] = '0';
                $address->isUpdate(true)->save();
            }
        }
    }
    public function poster()
    {
        if($this->request->isGet())
        {
            $data = [];
            $token = Secure::encrypt($this->business['mobile']);
            $data['link'] = "/business/login?token=$token";
            if(!is_file(ROOT_PATH.'public'.$this->business['poster'])){
                $avatar_text = $this->business['avatar_text'];
                $qrcode_text = QRcodeUtil::createQRcode($data['link'],$avatar_text);
                $status = PosterUtil::createPoster($this->business['nickname'],$avatar_text,$qrcode_text);
                if($status['code']){
                    $this->business['poster'] = $status['msg'];
                    $result = $this->business->save();
                    if($result){
                        $data['poster'] = $status['msg'];
                        $this->success('',null,$data);
                    }
                }
                $this->error('生成出错');
            }else{
                $data['poster'] = $this->business['poster'];
                $this->success('',null,$data);
            }
        }
        
    }
    public function team()
    {
        $parentid = $this->business['id'];
        $teamList = $this->model->where('parentid',$parentid)->select();
        return $teamList;
    }
    public function commission()
    {
        if($this->request->isGet())
        {
            $where = ['commission.parentid'=>$this->business['id'],'type'=>'product'];
            return Commission::with(['business'])->where($where)->select();
        }else if($this->request->isPut())
        {
            $recordModel = new Record();
            $id = $this->request->get('id',0,'trim');
            $commissionList = [];
            if(!$id){
                $commissionList = Commission::with(['business'])->where('status','0')->where('commission.parentid',$this->business['id'])->select();
            }else{
                $commission = Commission::with(['business'])->where('status','0')->where('commission.id',$id)->find();
                if(!$commission||$commission['parentid']!=$this->business['id'])$this->error('提现失败');
                $commissionList[] = $commission;
            }
            $result = false;
            Db::startTrans();
            try {
                foreach($commissionList as $commission)
                {
                    //business 加余额
                    $this->business['money'] += $commission['amount'];
                    $this->business->isUpdate()->save();
                    //commission 改为已提现
                    $commission['status'] = '1';
                    $commission->isUpdate()->save();
                    //record 添加记录
                    $params = [
                        'total'=>$commission['amount'],
                        'content'=>'提现了【'.$commission['business']['nickname'].'】的佣金￥'.$commission['amount'].'元',
                        'busid'=>$this->business['id']
                    ];
                    $result = $recordModel->create($params);
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error('提现失败');
            }
            $this->success('提现成功');
        }
    }
    public function record()
    {
        return Record::where('busid',$this->business['id'])->select();
    }
    public function recharge()
    {
        if($this->request->isGet())
        {
            $get = $this->request->get('get','','trim');
            if($get=='pay')
            {
                $this->success('',null,['wx'=>__('wechat').__('pay'),'zfb'=>__('alipay').__('pay')]);
            }else if($get=='paycode')
            {
                $orderModel = new Order();
                $type = $this->request->get('pay','','trim');
                $money = $this->request->get('money',0,'trim');
                if($money<0)$this->error('充值金额不能小于0');
                $pay = [
                    'amount'=>$money,
                    'qrcode'=>$orderModel->getPaycodeList()[$type],
                    'pay'=>$type
                ];
                $this->success('',null,$pay);
            }else{
                $this->error('请求错误');
            }
        }else if($this->request->isPost())
        {
            $orderModel = new Order();
            $payModel = new Pay();
            $payList = $orderModel->getPaycodeList();
            $money = $this->request->post('money',0,'trim');
            $type = $this->request->post('pay','','trim');
            if(floatval($money)<0||!isset($payList[$type]))$this->error('充值出错');
            $params = [
                'code'=>'PAY'.date('YmdHis',time()).Random::numeric(7),
                'name'=>'余额充值',
                'third'=>json_encode(['busid'=>$this->business['id']]),
                'type'=>$type,
                'total'=>$money,
                'price'=>$money,
                'cashier'=>'1',
                'status'=>'0',
                'qrcode'=>$payList[$type],
            ];
            $result = $payModel->create($params);
            if ($result === false) {
                $this->error('充值出错');
            }
            $this->success('',null,$result['id']);
        }else if($this->request->isPut())
        {
            $orderModel = new Order();
            $recordModel = new Record();
            $busid = $this->business['id'];
            $payid = $this->request->param('payid');
            $pay = Pay::where(['id'=>$payid])->find();
            if(!$pay||json_decode($pay['third'])->busid!=$busid)$this->error('订单不存在');
            $result = false;
            Db::startTrans();
            try {
                //pay 已支付
                $pay['status'] = '1';
                $pay->isUpdate()->save();
                //business 加余额
                $this->business['money'] += $pay['price'];
                $this->business->isUpdate()->save();
                //record 添加记录
                $payList = $orderModel->getPaycodeList();
                $params = [
                    'total'=>$pay['price'],
                    'content'=>$payList[$pay['type']].'支付充值了 '.$pay['price'].' 元',
                    'busid'=>$this->business['id']
                ];
                $result = $recordModel->create($params);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error('提现失败');
            }
            $this->success('提现成功');
        }
    }
    public function collection()
    {
        $pageSize = $this->request->get('pageSize',6,'trim');
        $page = $this->request->get('page',1,'trim');
        $list = Collection::where('busid',$this->business['id'])
                    ->where('status','product')
                    ->order('createtime','desc')
                    ->paginate($pageSize,$page);
        foreach ($list as $key => $item) {
            $list->offsetSet($key, $item['goods']);
        }
        return $list;
    }
    public function receive()
    {
        if($this->request->isGet())
        {
            $receiveid = $this->request->get('receiveid',0,'trim');
            $receive = $this->model->get($receiveid);
            if(!$receive)$this->error();
            $this->success('',null,$receive);
        }
    }
}
